<?php
declare(strict_types=1);

namespace App\Helper;

use Hyperf\HttpServer\Router\DispatcherFactory;
use Hyperf\HttpServer\Router\Handler;
use Hyperf\Server\Port;
use Hyperf\Utils\ApplicationContext;

class RouteHelper
{
    private static $routesAll = [];

    public static function getRouteByControllerAndMethod(string $controller, string $method): ?string
    {
        $routesAll = self::getRoutesAll();
        return $routesAll[$controller . '@' . $method] ?? null;
    }

    private static function getRoutesAll(): array
    {
        if (self::$routesAll) {
            return self::$routesAll;
        }
        $array = [];
        $serverName = ApplicationContext::getContainer()->get(Port::class)->getName();
        $routeCollector = ApplicationContext::getContainer()->get(DispatcherFactory::class)->getRouter($serverName);
        $routeData = $routeCollector->getData(); // print_r($routeData);
        /* @var Handler $handler */
        foreach ($routeData as $data) {
            foreach ($data as $routes) {
                foreach ($routes as $route => $handler) {
                    if (!$handler) {
                        continue;
                    }
                    $callback = ($handler->callback ?? null);
                    if (is_array($callback)) {
                        $key = implode('@', $callback);
                    } elseif (is_string($callback)) {
                        $key = $callback;
                    } else {
                        continue;
                    }
                    empty($key) || $array[$key] = $route;
                }
            }
        }
        self::$routesAll = $array;
        return $array;
    }
}
